package com.zzyl.intercept;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.MgtThreadLocal;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 管理端拦截器
 */
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenProperties jwtTokenProperties;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断当前请求是否是handler()
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //获取token
        String token = request.getHeader(Constants.USER_TOKEN);
        //token是否为空
        if (StringUtils.isEmpty(token)) {
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }

        //解析token
        Claims claims = JwtUtil.parseJWT(jwtTokenProperties.getSecretKey(), token);
        if (ObjectUtil.isEmpty(claims)) {
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }

        //获取用户数据
        String userJson = String.valueOf(claims.get("currentUser"));

        //获取用户数据
        Map userVo = JSONUtil.toBean(userJson, Map.class);

        //从redis获取url列表
        String key = CacheConstants.ACCESS_URLS + userVo.get("id");
        String urlJson = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isNotEmpty(urlJson)) {
            List<String> urlList = JSONUtil.toList(urlJson, String.class);
            //获取当前请求路径
            String targetUrl = request.getMethod() + request.getRequestURI();
            //匹配当前路径是否在urllist集合中
            for (String url : urlList) {
                if (antPathMatcher.match(url, targetUrl)) {
                    //存储到当前线程中
                    MgtThreadLocal.set(userJson);
                    return true;
                }
            }
        }
        throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MgtThreadLocal.remove();
    }
}
